<?php
namespace app\admin\controller;

class Index extends Base
{
    public function index()
    {
        $admin = model('admin')->get(session('admin_id'));
        if (is_null($admin)) {
            session('admin_id', null);
            cookie('admin_login', null);
            $this->redirect('/admin/login/login');
        }
        return $this->fetch('', [
            'modules'  => db('module')->where('type', 0)->order(['route'])->column('name', 'id'),
            'menulist' => $this->menu_list($admin),
            'username' => $admin->username,
        ]);
    }

    private function menu_list($admin)
    {
        $id = get_field('admin_role', $admin->role, 'auth');
        if ($id === '') {
            $id = [];
        } else {
            $id = explode(',', $id);
        }
        $where    = [];
        $modules  = db('module')->where('type', 0)->order(['route'])->column('id');
        $menulist = [];
        foreach ($modules as $module) {
            $menu = db('menu')->field(['id', 'name', 'route', 'icon'])->where(['parent_id' => 0, 'module' => $module, 'disabled' => 0]);
            if (!config('app_debug')) {
                $menu->where('id', '>=', 5);
            }
            if ($admin->id > 1) {
                $menu->where('id', '>=', 8)->whereOr('id',5);
            }
            if ($id) {
                $menu->whereIn('id', $id);
            }
            $menu_list = $menu->order(['sort' => 'desc'])->select();

            foreach ($menu_list as $k => $v) {
                if (!$v['route']) {
                    $sub = db('menu')->field(['id', 'name', 'route', 'icon'])->where(['parent_id' => $v['id'], 'module' => $module, 'disabled' => 0]);
                    if (!config('app_debug')) {
                        $sub->where('id', '>=', 5);
                    }
                    if ($admin->id > 1) {
                        $sub->where('id', '>=', 8);
                    }
                    if ($id) {
                        $sub->whereIn('id', $id);
                    }
                    $sub_list = $sub->order(['sort' => 'desc'])->select();
                   
                    if (empty($sub_list)) {
                        unset($menu_list[$k]);
                    } else {
                        $menu_list[$k]['sub'] = $sub_list;
                    }
                }
            }
            $menulist[] = $menu_list;
        }
        return $menulist;
    }
}
